import tensorflow as tf
print(tf.add(1,2))
print(tf.add([1,2],[3,4]))
print(tf.square(5))
print(tf.reduce_sum([1,2,3]))

x = tf.matmul([[1]],[[2,3]])
print(x)
print(x.shape)
print(x.dtype)

import numpy as np
ndarray = np.ones([3,3])

print("TensorFlow operations convert numpy arrays to Tensors automatically")
tensor = tf.multiply(ndarray,42)
print(tensor)

print("And NumPy operations convert Tensors to numpy arrays automatically")
print(np.add(tensor,1))

print("The .numpy() method explicitly converts a Tensor to a numpy array")
print(tensor.numpy())

x = tf.random.uniform([3,3])

print('Is there a Gpu availabel:')
print(tf.test.is_gpu_available())

#在TensorFlow中，placement (放置)指的是如何分配（放置）设备以执行各个操作，如上所述，如果没有提供明确的指导，
# TensorFlow会自动决定执行操作的设备，并在需要时将张量复制到该设备。但是，
# 可以使用 tf.device 上下文管理器将TensorFlow操作显式放置在特定设备上，例如：

import time

def time_matmul(x):
    start = time.time()
    for loop in range(10):
        tf.matmul(x,x)
    result = time.time() - start
    print("10 loops: {:0.2f}ms".format(1000 * result))

print("On CPU:")
with tf.device('CPU:0'):
    x = tf.random.uniform([1000,1000])
    assert x.device.endswith('CPU:0')
    time_matmul(x)


#使用其中一个工厂函数（如 Dataset.from_tensors, Dataset.from_tensor_slices）
# 或使用从TextLineDataset 或 TFRecordDataset 等文件读取的对象创建源数据集。
ds_tensors = tf.data.Dataset.from_tensor_slices([1,2,3,4,5,6])

# Create a CSV file
import tempfile
_,filename = tempfile.mkstemp()

with open(filename,'w') as f:
    f.write("""Line 1
    Line 2
    Line 3
    """)
ds_file = tf.data.TextLineDataset(filename)
ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)
ds_file = ds_file.batch(2)

print("Elements of ds_tensors:")
for x in ds_tensors:
    print(x)

print("\nElement in ds_file:")
for x in ds_file:
    print(x)




